﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DemoObject;
using BusinessObjects;
using HTT.Utility;

public partial class TemplateAE : System.Web.UI.UserControl
{
    public Guid TemplateId { get; set; }
    public bool IsHtml { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request["TemplateId"] != null)
        {
            TemplateId = new Guid(Request["TemplateId"].ToString());
            btnUpdate.Text = "Cập nhật";
        }
        else TemplateId = Guid.Empty;
        if (Request["IsHtml"] != null)
            IsHtml = bool.Parse(Request["IsHtml"]);
        else
            IsHtml = false;
        if (!IsPostBack)
        {
            LoadData();
        }
    }
    private void LoadData()
    {
        if (!TemplateId.Equals(Guid.Empty))
        {
            TblTemplate item = TblTemplateRepository.CreateInstant().SelectOne(TemplateId);
            if (item != null)
            {
                txtName.Text = item.Name;
                txtDescription.Value = item.Description;
                cbIsVisible.Checked = item.IsVisible;
                if (IsHtml)
                    txtDescription.Value = item.Description;
                else txtDescriptionNoHtml.Text = item.Description;
                lblCreatedBy.Text = item.CreatedBy;
                lblCreatedDate.Text = item.CreatedDate.ToString("dd/MM/yyyy");
                lblUpdatedBy.Text = item.UpdatedBy;
                lblUpdatedDate.Text = item.UpdatedDate.ToString("dd/MM/yyyy");
            }
        }
    }
    private TblTemplate GetTblTemplate()
    {
        TblTemplate obj = TblTemplateRepository.CreateInstant().SelectOne(TemplateId);
        if (obj == null)
        {
            obj = new TblTemplate();
            obj.Id = Guid.NewGuid();
            obj.TextId = TblTemplateRepository.CreateInstant().GetUniqueTextIdFromUnicodeText(txtName.Text, 1000);
            obj.CreatedBy = HttpContext.Current.User.Identity.Name;
            obj.CreatedDate = DateTime.Now;
        }
        obj.Name = txtName.Text;
        if (IsHtml)
            obj.Description = UnicodeConversion.CreateInstant().CleanUpWordHtml(txtDescription.Value);
        else obj.Description = txtDescriptionNoHtml.Text.Trim();
        obj.IsVisible = cbIsVisible.Checked;
        obj.UpdatedBy = HttpContext.Current.User.Identity.Name;
        obj.UpdatedDate = DateTime.Now;

        return obj;
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        if (TemplateId.Equals(Guid.Empty))
            TblTemplateRepository.CreateInstant().Insert(GetTblTemplate());
        else
            TblTemplateRepository.CreateInstant().Update(GetTblTemplate());
        Response.Redirect("TemplateList.aspx");
    }


}
